//
//  MusicControl.swift
//  MusicControl
//
//  Created by nkl on 2024/10/15.
//

import SwiftUI
import WidgetKit

// 1. 数据模型
struct SimpleEntry: TimelineEntry {
    let date: Date
}

// 2. 提供器：定义时间线，何时刷新数据
struct Provider: IntentTimelineProvider {
    typealias Intent = WidgetTypeIntentIntent

    typealias Entry = SimpleEntry

    func placeholder(in context: Context) -> SimpleEntry {
        SimpleEntry(date: Date())
    }

    func getSnapshot(for configuration: WidgetTypeIntentIntent, in context: Context, completion: @escaping @Sendable (SimpleEntry) -> Void) {
        let entry = SimpleEntry(date: Date())
        completion(entry)
    }

    func getTimeline(for configuration: WidgetTypeIntentIntent, in context: Context, completion: @escaping @Sendable (Timeline<SimpleEntry>) -> Void) {
        var entries: [SimpleEntry] = []

        // 创建未来 5 小时的时间线
        for hourOffset in 0 ..< 5 {
            let entryDate = Calendar.current.date(byAdding: .hour, value: hourOffset, to: Date())!
            let entry = SimpleEntry(date: entryDate)
            entries.append(entry)
        }

        // 创建时间线
        let timeline = Timeline(entries: entries, policy: .atEnd)
        completion(timeline)
    }
}

// 3. Widget 的 SwiftUI 视图
struct SimpleWidgetEntryView: View {
    @Environment(\.widgetFamily) var family
    var entry: Provider.Entry

    var body: some View {
        switch family {
        case .systemSmall:
            SmallWidget()
        case .systemMedium:
            MediumWidget()
        case .systemLarge:
            LargeWidget()
        default:
            SmallWidget()
        }
    }
}

struct SmallWidget: View {
    var body: some View {
        Small_MusicCD03_02()
    }
}

struct MediumWidget: View {
    var body: some View {
        Medium_MusicCD03_01()
    }
}

struct LargeWidget: View {
    var body: some View {
        HStack {
            MusicCDWidget(hasArrow: false)
            Text("Test ===== LargeWidget")
        }
    }
}

// 4. Widget 定义
struct SimpleWidget: Widget {
    let kind: String = "SimpleWidget"

    var body: some WidgetConfiguration {
        IntentConfiguration(kind: kind, intent: WidgetTypeIntentIntent.self, provider: Provider()) { entry in
            SimpleWidgetEntryView(entry: entry)
        }
        .contentMarginsDisabled()
        .configurationDisplayName("选择一个Widget吧")
        .description("选择一个Widget吧，老倪牛逼")
        .supportedFamilies([.systemSmall, .systemMedium, .systemLarge]) // 支持不同大小的组件
    }
}
